package com.leyou.interceptor;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.config.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProps;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取用户Token
        // 参数一:request;参数二:用cookie名生成token
        String userToken = CookieUtils.getCookieValue(request,jwtProps.getCookie().getCookieName());

        // 2.验证用户Token 获取token中的用户信息
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(userToken,jwtProps.getPublicKey(),UserInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        // 3.取出登录用户信息UserInfo
        UserInfo userInfo = payload.getInfo();

        // 4.把UserInfo存入ThreadLocal
        UserHolder.setUser(userInfo);
        //放行
        return true;
    }
}
